package com.dms.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.dms.bean.Student;
import com.dms.model.StudentModel;


/**
 * Servlet implementation class loginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		this.doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		 response.setContentType("text/html");
		 response.setCharacterEncoding("UTF-8");
	   	 request.setCharacterEncoding("UTF-8");
	   	String action = request.getParameter("act");
		if (action == null)
			action = "";
		if (action.equals("login")) {
			this.login(request, response);
		}
		if (action.equals("logout")) {
			this.logout(request, response);
		}

	}
	
	protected void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Student Student = new Student();
		Student.setStuID(request.getParameter("ID"));
		Student.setPassword(request.getParameter("password"));
		//System.out.print("test");
		boolean val = StudentModel.login(Student);
//		boolean val =false;
		if (!val) {
			request.setAttribute("message", "登录失败，学号或密码错误");
			request.getRequestDispatcher("login2.jsp").forward(request, response);
		} else {
			HttpSession session = request.getSession();
			session.setAttribute("student", Student);
			response.sendRedirect("IndexServlet?act=index");
		}
	}
	
	protected void logout(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		HttpSession session = request.getSession();
		session.removeAttribute("Student");
		session.invalidate();
		response.sendRedirect("login2.jsp");
	}

}
